package com.myfoon.servlet.pub;

import com.myfoon.model.entity.Photo;

import java.io.IOException;

import java.io.PrintWriter;

import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONObject;

public class RemoveAttachment extends HttpServlet {
    public RemoveAttachment() {
    }


    @Override
    protected void doPost(HttpServletRequest httpServletRequest,
                          HttpServletResponse httpServletResponse) throws ServletException,
                                                                          IOException {
        
        String id = httpServletRequest.getParameter("id");        
        String type = httpServletRequest.getParameter("type");
            
        PrintWriter writer = httpServletResponse.getWriter();
        
        if (id == null || type == null || id.length() == 0 || type.length() == 0) {
            writer.println("0");    
            System.out.println(0);
            return;
        }
        
        if (type.equals("img")) {
            Object attachedImagesObj = httpServletRequest.getSession(true).getAttribute("attachedImages");
            if (attachedImagesObj == null) {
                writer.println("1");
                System.out.println(1);
                return;
            }
            
            List<Photo> attachedImagesList = (List<Photo>)attachedImagesObj;
            
            Photo removedPhoto = null;
            for (Photo p : attachedImagesList) {
                if (p.getTempId().equals(id)) {
                    removedPhoto = p;
                }            
            }
            if (removedPhoto != null) {
                attachedImagesList.remove(removedPhoto);
            }
            
            System.out.println(attachedImagesList.size());
            httpServletRequest.getSession(true).setAttribute("attachedImages", attachedImagesList);  
            writer.println("2");   
            System.out.println(2);
        }                   
    }
}
